package org.ww.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.ww.common.exception.GmallExceptionEnum;
import org.ww.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: gmall
 * @description: 异常处理
 * @author: ww
 * @create: 2024-01-12 15:47
 **/
@Slf4j
@RestControllerAdvice(basePackages = "org.ww.product.controller")
public class ExceptionController {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validException(MethodArgumentNotValidException e){

        Map<String,String> errorMap = new HashMap<>();

        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return R.error(GmallExceptionEnum.VALIDATION_EXCEPTION.getCode(),GmallExceptionEnum.VALIDATION_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R Exception(Throwable e){

        return R.error(GmallExceptionEnum.UNKNOW_EXCEPTION.getCode(),GmallExceptionEnum.UNKNOW_EXCEPTION.getMsg());
    }

}
